package com.inner;

import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * 加签解签
 * @author wuwenzhe
 * 
 */
public class SignatureUtils {

	/**
	 * 私钥签名
	 * 
	 * @param data
	 *            待签名数据
	 * @param priKey
	 *            签名私钥 PKCS8Encoded
	 * @return 签名结果
	 * @throws Exception
	 */
	public static byte[] sign(byte[] data, byte[] priKey) {
		byte[] sign=null;
		try{
			PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(priKey);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
	
			//对数据进行SHA-256签名
			MessageDigest md= MessageDigest.getInstance("SHA-256");
			byte[] sha256Digest=md.digest(data);
			
			Signature instance = Signature.getInstance("SHA1withRSA");
			instance.initSign(privateKey);
			instance.update(sha256Digest);
			sign = instance.sign();
		}catch(Exception e){
			throw new RuntimeException(e);
		}
		return sign;
	}

	/**
	 * 验证签名
	 * 
	 * @param data
	 *            待验签数据
	 * @param pubkey
	 *            公钥
	 * @param sign
	 *            签名
	 * @return
	 * @throws Exception
	 */
	public static boolean verify(byte[] data, byte[] pubkey, byte[] sign){
		boolean result=false;
		try{
			// 获取公钥对象
			X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(pubkey);
			KeyFactory keyFactory = java.security.KeyFactory.getInstance("RSA");
			PublicKey pubKey = keyFactory.generatePublic(bobPubKeySpec);

			//对数据进行SHA-256签名
			MessageDigest md= MessageDigest.getInstance("SHA-256");
			byte[] sha256Digest=md.digest(data);
			//System.out.println("sha256Digest"+Hex.encodeHexString(sha256Digest));
			//System.out.println("sign"+Hex.encodeHexString(sign));
			// 验证签名
			Signature instance = Signature.getInstance("SHA1withRSA");
			instance.initVerify(pubKey);
			instance.update(sha256Digest);
			result = instance.verify(sign);
		}catch(Exception e){
			throw new RuntimeException(e);
		}
		return result;
	}
}
